// frontend/src/admin/ConsumptionManagement.js

import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, Select, InputNumber, DatePicker, message, Space, Popconfirm } from 'antd';
import { adminAPI } from '../services/api';
import moment from 'moment';

const { Option } = Select;

const ConsumptionManagement = () => {
    const [form] = Form.useForm();
    const [consumptions, setConsumptions] = useState([]);
    const [loading, setLoading] = useState(false);
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [activeCheckins, setActiveCheckins] = useState([]); // For checkin dropdown
    const [menuItems, setMenuItems] = useState([]); // For menu item dropdown
    const [selectedMenuItemPrice, setSelectedMenuItemPrice] = useState(0); // To calculate amount
    const [currentCheckinId, setCurrentCheckinId] = useState(null); // Track selected checkin for displaying its consumptions

    useEffect(() => {
        fetchActiveCheckins();
        fetchMenuItems();
    }, []);

    // Fetch active check-ins for the dropdown
    const fetchActiveCheckins = async () => {
        try {
            const response = await adminAPI.getActiveCheckins();
            setActiveCheckins(response);
        } catch (error) {
            message.error('获取入住中记录失败: ' + (error.response?.data?.message || error.message));
        }
    };

    // Fetch menu items for the dropdown
    const fetchMenuItems = async () => {
        try {
            const response = await adminAPI.getAllMenuItems();
            setMenuItems(response);
        } catch (error) {
            message.error('获取菜单项失败: ' + (error.response?.data?.message || error.message));
        }
    };

    // Fetch consumptions for a specific check-in
    const fetchConsumptionsByCheckin = async (checkinId) => {
        if (!checkinId) {
            setConsumptions([]);
            return;
        }
        setLoading(true);
        try {
            const response = await adminAPI.getConsumptionsByCheckin(checkinId);
            setConsumptions(response);
        } catch (error) {
            message.error('获取消费记录失败: ' + (error.response?.data?.message || error.message));
            console.error('Error fetching consumptions:', error);
        } finally {
            setLoading(false);
        }
    };

    const handleCheckinChange = (value) => {
        setCurrentCheckinId(value);
        fetchConsumptionsByCheckin(value);
    };

    const showModal = () => {
        form.resetFields();
        setSelectedMenuItemPrice(0); // Reset price
        form.setFieldsValue({ consume_time: moment() }); // Default consume time to now
        setIsModalVisible(true);
    };

    const handleCancel = () => {
        setIsModalVisible(false);
    };

    const handleMenuItemChange = (value) => {
        const selectedItem = menuItems.find(item => item.item_id === value);
        if (selectedItem) {
            setSelectedMenuItemPrice(selectedItem.price);
            // Calculate total amount based on quantity
            const quantity = form.getFieldValue('quantity') || 1; // Default quantity to 1 if not set
            form.setFieldsValue({ amount: quantity * selectedItem.price });
        } else {
            setSelectedMenuItemPrice(0);
            form.setFieldsValue({ amount: 0 });
        }
    };

    const handleQuantityChange = (quantity) => {
        if (quantity !== null && !isNaN(quantity)) {
            form.setFieldsValue({ amount: quantity * selectedMenuItemPrice });
        } else {
            form.setFieldsValue({ amount: 0 });
        }
    };

    const onFinish = async (values) => {
        try {
            // 确保 checkin_id 已经被选中
            if (!currentCheckinId) {
                message.error('请先选择一个入住记录');
                return;
            }

            const selectedMenuItem = menuItems.find(item => item.item_id === values.item_id);
            if (!selectedMenuItem) {
                message.error('请选择有效的商品');
                return;
            }

            const consumptionData = {
                checkin_id: currentCheckinId, // 使用当前选中的入住记录ID
                item_name: selectedMenuItem.item_name, // 确保传递的是 item_name
                quantity: values.quantity,
                amount: values.amount,
                consume_time: values.consume_time.format('YYYY-MM-DD HH:mm:ss') // 格式化时间
            };

            await adminAPI.addConsumption(consumptionData);
            message.success('消费记录添加成功');
            form.resetFields();
            setIsModalVisible(false);
            fetchConsumptionsByCheckin(currentCheckinId); // 刷新当前入住记录的消费列表
        } catch (error) {
            message.error('添加消费记录失败: ' + (error.response?.data?.message || error.message));
            console.error('Error adding consumption:', error);
        }
    };

    const columns = [
        { title: '商品名称', dataIndex: 'item_name', key: 'item_name' },
        { title: '数量', dataIndex: 'quantity', key: 'quantity' },
        { title: '金额', dataIndex: 'amount', key: 'amount' },
        { title: '消费时间', dataIndex: 'consume_time', key: 'consume_time' },
        // {
        //     title: '操作',
        //     key: 'action',
        //     render: (_, record) => (
        //         <Space size="middle">
        //             {/* Add edit/delete functionality if needed */}
        //         </Space>
        //     ),
        // },
    ];

    return (
        <div style={{ padding: 24 }}>
            <h2>消费管理</h2>
            <div style={{ marginBottom: 16 }}>
                <Form layout="inline">
                    <Form.Item label="选择入住记录">
                        <Select
                            showSearch
                            placeholder="选择入住记录 (房间号 - 客户姓名)"
                            style={{ width: 280 }}
                            onChange={handleCheckinChange}
                            optionFilterProp="children"
                            // 修正 filterOption，确保 children 是字符串
                            filterOption={(input, option) => {
                                const childrenText = String(option.children || '');
                                return childrenText.toLowerCase().includes(input.toLowerCase());
                            }}
                        >
                            {activeCheckins.map(checkin => (
                                <Option key={checkin.checkin_id} value={checkin.checkin_id}>
                                    {checkin.room_number} - {checkin.guest_name}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" onClick={showModal} disabled={!currentCheckinId}>
                            新增消费
                        </Button>
                    </Form.Item>
                </Form>
            </div>


            <Table
                columns={columns}
                dataSource={consumptions}
                rowKey="consumption_id"
                loading={loading}
                pagination={false} // No pagination for consumption list as it's for one checkin
                locale={{ emptyText: currentCheckinId ? '暂无消费数据' : '请先选择入住记录' }}
            />

            <Modal
                title="新增消费记录"
                visible={isModalVisible}
                onCancel={handleCancel}
                footer={null}
            >
                <Form
                    form={form}
                    layout="vertical"
                    onFinish={onFinish}
                >
                    <Form.Item
                        name="item_id"
                        label="商品名称"
                        rules={[{ required: true, message: '请选择商品' }]}
                    >
                        <Select
                            showSearch
                            placeholder="选择商品"
                            onChange={handleMenuItemChange}
                            optionFilterProp="children"
                            // 修正 filterOption，确保 children 是字符串
                            filterOption={(input, option) => {
                                const childrenText = String(option.children || '');
                                return childrenText.toLowerCase().includes(input.toLowerCase());
                            }}
                        >
                            {menuItems.map(item => (
                                <Option key={item.item_id} value={item.item_id}>
                                    {item.item_name} - ¥{item.price}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="quantity"
                        label="数量"
                        rules={[{ required: true, message: '请输入数量' }, { type: 'number', min: 1, message: '数量必须大于0' }]}
                    >
                        <InputNumber min={1} style={{ width: '100%' }} onChange={handleQuantityChange} />
                    </Form.Item>
                    <Form.Item
                        name="amount"
                        label="金额"
                    >
                        <InputNumber disabled style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item
                        name="consume_time"
                        label="消费时间"
                        rules={[{ required: true, message: '请选择消费时间' }]}
                    >
                        <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" htmlType="submit">
                            添加
                        </Button>
                        <Button onClick={handleCancel} style={{ marginLeft: 8 }}>
                            取消
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
};

export default ConsumptionManagement;